package de.dfki.asr.genesis2.sms.util;

import java.util.ArrayList;

import com.thoughtworks.xstream.annotations.XStreamAsAttribute;

public class Point {
	@XStreamAsAttribute
	private Double latitude = null;
	
	@XStreamAsAttribute
	private Double longitude = null;
	
	private Double altitude = null;
	
	public Point (double latitude, double longitude) {
		this.latitude = latitude;
		this.longitude = longitude;
	}
	
	public static boolean validLocation(String location) {
		try {
			String latlong[] = location.split(",");
			String latString = latlong[0];
			String lonString = latlong[1];
			double lat = Double.parseDouble(latString);
			double lon = Double.parseDouble(lonString);
			if (lon>=-180 && lon<=180 && lat>=-90 && lat<=90)
				return true;
		}
		catch (NumberFormatException e) {
		}
		catch (ArrayIndexOutOfBoundsException e) {
		}
		return false;
		
	}
	
	@Override 
	public String toString() {
		return this.latitude + "," + this.longitude;
	}
	
	
    public MapTile getTileNumber(int zoom) {
 	   int xtile = (int)Math.floor( (this.longitude + 180) / 360 * (1<<zoom) ) ;
 	   int ytile = (int)Math.floor( (1 - Math.log(Math.tan(Math.toRadians(this.latitude)) + 1 / Math.cos(Math.toRadians(this.latitude))) / Math.PI) / 2 * (1<<zoom) ) ;
 	   return new MapTile(xtile, ytile, zoom);
    }
    
    public boolean inMapTile(MapTile tile) {
    	return tile.equals(this.getTileNumber(tile.getZoom()));
    }
    
    public boolean inMapTiles(ArrayList<MapTile> tiles) {
    	for (MapTile tile: tiles) {
    		if (this.inMapTile(tile)) {
    			return true;
    		}
    	}
    	return false;
    }

	public String getCoordinate() {
		return Double.toString(this.latitude) + "," + Double.toString(this.longitude);
	}
	
	public double getLatitude() {
		return this.latitude;
	}
	
	public double getLongitude() {
		return this.longitude;
	}
	
	void setLatitude(double latitude) {
		this.latitude = latitude;
	}
	
	void setLongitude(double longitude) {
		this.longitude = longitude;
	}

	public double getAltitude() {
		return altitude;
	}

	public void setAltitude(double altitude) {
		this.altitude = altitude;
	}
	
	
	
	public static void main(String args[]) throws Exception
    {
		double longitude=-122.75;
		double latitude=36.8;
		Point p = new Point(latitude,longitude);
		System.out.println("SF: " + p.getTileNumber(10).toString());
		longitude=-74;
		latitude=40;
		p = new Point(latitude,longitude);
		System.out.println("NY: " + p.getTileNumber(10).toString());
		longitude=5.50;
		latitude=47.10;
		p = new Point(latitude,longitude);
		System.out.println("BE: " + p.getTileNumber(10).toString());
		
		
    }
	
}

